<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Fetch API 获取数据</title>
    <style>
        body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; background-color: #f4f4f9; color: #333; }
        #container { max-width: 900px; margin: 30px auto; background: white; padding: 25px; border-radius: 8px; box-shadow: 0 4px 12px rgba(0,0,0,0.1); }
        h1 { text-align: center; color: #333; margin-bottom: 20px; }
        .table { width: 100%; border-collapse: collapse; }
        .table th, .table td { border: 1px solid #e0e0e0; padding: 15px; text-align: center; vertical-align: middle; }
        .table th { background-color: #f8f9fa; font-weight: 600; }
        .avatar { width: 60px; height: 60px; object-fit: cover; border-radius: 50%; border: 2px solid #ddd; }
    </style>
</head>
<body>

<div id="container">
    <h1>超级英雄名册 (数据来自Ajax)</h1>
    <table class="table">
        <thead>
        <tr>
            <th>英雄名</th><th>头像</th><th>真名</th><th>阵营</th><th>首次登场</th>
        </tr>
        </thead>
        <tbody>
        <tr v-for="hero in heroList" :key="hero.id">
            <td>{{ hero.name }}</td><td><img :src="hero.image" class="avatar" :alt="hero.name"></td><td>{{ hero.alias }}</td><td><span v-if="hero.publisher === 'Marvel'">漫威</span><span v-else-if="hero.publisher === 'DC'">DC</span></td><td>{{ hero.firstAppearance }}</td>
        </tr>
        </tbody>
    </table>
</div>
<script type="module">
    import { createApp } from 'https://unpkg.com/vue@3/dist/vue.esm-browser.js';

    createApp({
        data() {
            return {
                // 1. 初始时，英雄列表为空数组
                heroList: []
            }
        },
        methods: {
            // 2. 将 fetch 逻辑封装成一个方法
            fetchHeroes() {
                fetch('https://m1.apifoxmock.com/m1/2009950-1827561-default/heros') // 请求同目录下的 heroes.json 文件
                    .then(response => response.json())
                    .then(data => {
                        // 3. 请求成功后，将获取的数据赋值给 heroList
                        console.log('成功获取数据:', data);
                        this.heroList = data;
                    })
                    .catch(error => {
                        console.error('获取英雄列表失败:', error);
                    });
            }
        },
        // 4. mounted 钩子会在组件挂载到页面后执行
        mounted() {
            console.log('组件已挂载，开始获取数据...');
            // 调用 methods 中的方法来执行请求
            this.fetchHeroes();
        }
    }).mount('#container');
</script>
</body>
</html>
